package edu.lingnan.store.service.impl;

import edu.lingnan.store.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Service("mailService")
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    private final String MAIL_FORM = "3368285353@qq.com";
    private final String MAIL_FORM_NICK = "712便利店";

    /**
     * 发送验证码
     * @param mailTo        收件人邮箱
     * @param cc            抄送邮箱
     * @param subject       主题
     * @param content       内容
     */
    @Override
    public void sendCodeMail(String mailTo, String cc, String subject, String content) {
        try {
            //简单邮件信息类
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //html邮件信息类
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            //昵称
            mimeMessageHelper.setFrom(new InternetAddress(MAIL_FORM_NICK + "<" + MAIL_FORM + ">"));
            mimeMessageHelper.setTo(mailTo);
            if(!StringUtils.isEmpty(cc)){
                mimeMessageHelper.setCc(cc);
            }
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);

            mailSender.send(mimeMessage);
        }catch (Exception e){
            logger.error("发件失败：",e);
        }
    }
}
